package org.pro.bookkeeping.core.service.impl;

import java.util.Date;

import org.pro.bookkeeping.core.common.ProcException;
import org.pro.bookkeeping.core.common.util.Md5encode;
import org.pro.bookkeeping.core.common.util.StringUtil;
import org.pro.bookkeeping.core.common.util.TransactionAspectUtil;
import org.pro.bookkeeping.core.dao.AccountDao;
import org.pro.bookkeeping.core.dao.UserDao;
import org.pro.bookkeeping.core.pojo.Account;
import org.pro.bookkeeping.core.pojo.User;
import org.pro.bookkeeping.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional(rollbackFor = Exception.class)
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private AccountDao accountDao;

	private Integer retCode = 0;
	private String ExceptionInfo = null;

	public String regist(String loginName, String password, String userName, String mobilephone) {

		User user = new User();
		user.setLoginName(loginName);
		user.setPassword(Md5encode.generatePassword(password));
		user.setUserName(userName);
		user.setMobilephone(mobilephone);
		try {
			User u = userDao.findUserByLoginName(user);
			if (u != null) {
				throw new ProcException("该账户已存在");

			} else {
				userDao.InsertOneUser(user);
				Account account = new Account();
				account.setLastUpdateTime(StringUtil.simpleDateFormat.format(new Date()));
				account.setMoney("0");
				account.setUserID(user.getUserID());
				accountDao.inserOneAccount(account);
			}
		} catch (Exception e) {
			retCode = 1;
			ExceptionInfo = e.getMessage();
			e.printStackTrace();
			TransactionAspectUtil.RollbackException();

		}
		return StringUtil.WriteJson(retCode, ExceptionInfo, null);
	}
	public String login(String loginName, String password) {
		User user = new User();
		user.setLoginName(loginName);
		User u = userDao.findUserByLoginName(user);
		try {
			if (u == null) {
				throw new ProcException("用户不存在");

			} else {
				if (!Md5encode.validatePassword(u.getPassword(), password)) {
					u = null;
					throw new ProcException("密码错误");
				}
			}
		} catch (Exception e) {
			retCode = 1;
			ExceptionInfo = e.getMessage();
			e.printStackTrace();
			TransactionAspectUtil.RollbackException();
		}

		return StringUtil.WriteJson(retCode, ExceptionInfo, u);
	}

}
